<template>
  <el-dialog
    v-dialogDrag
    :visible.sync="dialogVisible"
    :title="title"
    width="950px"
    @close="resetForm('ruleForm')"
  >
    <button-group
      ref="buttonGroup"
      @deleteCancel="deleteCancel"
      @submitForm="submitForm('ruleForm')"
      @cancel="dialogVisible = false"
    />
    <div class="formTopFont">销售订单</div>
    <el-row>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="销售单号" prop="saleNo">
              <el-input
                v-model="ruleForm.saleNo"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select v-model="ruleForm.customerId" style="width: 100%">
                <el-option
                  v-for="item in customerAllList"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="接单日期" prop="saleDate">
              <el-date-picker
                v-model="ruleForm.saleDate"
                type="date"
                placeholder="选择日期时间"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售交期" prop="deliveryDate">
              <el-date-picker
                v-model="ruleForm.deliveryDate"
                type="date"
                placeholder="选择日期时间"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="销售人" prop="userId">
              <el-select v-model="ruleForm.userId" style="width: 100%">
                <el-option
                  v-for="item in userAllList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                maxlength="200"
                type="textarea"
                rows="3"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        border
        stripe
        class="tabOver"
        height="220px"
        :data="ruleForm.materials"
      >
        <el-table-column prop="materialId" align="center">
          <template slot="header">
            <span style="color: #f56c6c">*</span>物料
          </template>
          <template #default="{ row, $index }">
            <!-- 展示物料名称-物料编号-规格-单位 -->
            <el-select
              v-model="row.materialId"
              size="mini"
              style="width: 100%"
              filterable
              @change="selectWhseList(row, $index)"
            >
              <el-option
                v-for="item in materialAll"
                :key="item.id"
                :value="item.id"
                :label="
                  item.materialName +
                  `${
                    item.materialCode !== ''
                      ? '-【' + item.materialCode + '】'
                      : ''
                  }`
                "
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          width="100px"
          align="center"
        />
        <el-table-column
          prop="specifications"
          label="规格"
          width="100px"
          align="center"
        />
        <el-table-column prop="askDate" align="center" width="185px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>交货日期
          </template>
          <template #default="{ row }">
            <el-date-picker
              v-model="row.askDate"
              size="mini"
              type="datetime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="num" align="center" width="100px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>订单数量
          </template>
          <template #default="{ row }">
            <el-input-number
              v-model="row.num"
              size="mini"
              :controls="false"
              :min="1"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="price" align="center" width="100px">
          <template slot="header">
            <span style="color: #f56c6c">*</span>单价
          </template>
          <template #default="{ row }">
            <el-input-number
              v-model="row.price"
              size="mini"
              :controls="false"
              :precision="2"
              :min="1"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px" align="center">
          <template #default="{ $index }">
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="ruleForm.materials.splice($index, 1)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button
        style="width: 100%"
        @click="ruleForm.materials.push({ ...basicParams })"
        >添加</el-button
      >
    </el-row>
    <bottom-font
      v-if="title === '编辑'"
      ref="bottomFont"
      :obj-name="ruleForm.userName"
      :rew-name="ruleForm.reviewer"
      :obj-date="ruleForm.saleDate"
    />
  </el-dialog>
</template>
<script>
import bottomFont from "@/components/BottomFont";
export default {
  components: { bottomFont },
  props: {
    materialAll: {
      type: Array,
      default: () => {
        return [];
      },
    },
    userAllList: {
      type: Array,
      default: () => {
        return {};
      },
    },
  },
  data() {
    const checkSaleNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/sale/order/verifyNoUnique?no=${value}&id=${this.ruleForm.id || ""}`
      );
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback("销售单号重复！"));
      } else {
        return new Error(callback(res.data.msg));
      }
    };
    const params = {
      askDate: "",
      materialId: "",
      num: "",
      price: "",
    };
    return {
      title: "",
      ruleForm: {
        customerId: "", // 客户名称
        saleNo: "", // 销售单号
        materialId: "",
        userId: "", // 收货人主键
        saleDate: "", // 接单日期
        remark: "", // 描述
        materials: [],
        deliveryDate: "", // 销售交期
      },
      rules: {
        saleNo: [
          { required: true, message: "销售单号不能为空！", trigger: "blur" },
          { validator: checkSaleNo, trigger: "blur" },
        ],
        materialId: [
          { required: true, message: "物料不能为空！", trigger: "change" },
        ],
      },
      dialogVisible: false,
      basicParams: params,
      customerAllList: [],
      obj: {},
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.obj = row;
      this.getCustomerData();
      if (row && row.hasOwnProperty("id")) {
        this.title = "编辑";
        const res = await this.$axios.get(`/sale/order/detail?id=${row.id}`);
        if (res?.data.code === 200) {
          this.ruleForm = Object.assign({}, res.data.data);
        }
      } else {
        this.title = "新增";
      }
      this.dialogVisible = true;
    },
    /**
     * @description: 获取所有启用的客户信息
     * @return {*}
     */
    async getCustomerData() {
      const res = await this.$axios.get("/basic/customer/allBySave");
      this.customerAllList = [
        { id: "0", customerName: "无" },
        ...res.data.data,
      ];
    },
    /* 物料选择 */
    selectWhseList(row, index) {
      row.num = "";
      row.unit = "";
      row.specifications = "";
      row.model = "";
      const { unit, specifications, model, num } = this.materialAll.find(
        (item) => item.id === row.materialId
      );
      row.unit = unit;
      row.specifications = specifications;
      row.model = model;
      row.num = num;
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.ruleForm.materials.length > 0) {
            const hasEmptyList = [];
            this.ruleForm.materials.forEach((item, index) => {
              if (
                !item.materialId ||
                !item.num ||
                !item.askDate ||
                !item.price
              ) {
                hasEmptyList.push(index + 1);
              }
            });
            console.log(hasEmptyList, this.ruleForm);
            if (hasEmptyList.length) {
              this.$alert(
                `请完善记录，序号：${hasEmptyList
                  .toString()
                  .replace(/,/g, "、")} !`,
                "提示",
                {
                  confirmButtonText: "确认",
                  type: "warning",
                }
              );
            } else {
              const params = {
                ...this.ruleForm,
                orderMaterials: this.ruleForm.materials,
              };
              const res = await this.$axios.post("/sale/order/save", params);
              if (res?.data.code === 200) {
                this.$notify.success("提交成功！");
                this.dialogVisible = false;
                this.$emit("getTableInfo");
              } else {
                this.$notify.error(res.data.msg);
              }
            }
          } else {
            this.$alert(`请至少添加一条物料信息!`, "提示", {
              confirmButtonText: "确认",
              type: "warning",
            });
          }
        }
      });
    },
    async deleteCancel() {
      if (this.title === "编辑") {
        this.$confirm(`确认删除数据？`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .delete(`/sale/order/remove/${this.obj.id}`)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$notify.success("删除成功！");
                  this.dialogVisible = false;
                  this.$emit("getTableInfo", 1);
                } else {
                  this.$notify.error(res.data.msg);
                }
              });
          })
          .catch(() => {});
      }
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm);
    },
  },
};
</script>
<style lang="scss" scoped></style>
